package com.hospital.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

@Slf4j
@Component
public class DrugModuleDataInitializer {

    private final JdbcTemplate jdbcTemplate;

    @Value("${spring.datasource.url:}")
    private String dsUrl;

    public DrugModuleDataInitializer(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @jakarta.annotation.PostConstruct
    public void init() {
        try {
            // 尝试查询任一新模块表，若不存在则执行建表脚本
            try {
                jdbcTemplate.queryForList("SELECT 1 FROM drugCategory LIMIT 1");
                // 表存在则不初始化
                return;
            } catch (Exception e) {
                log.info("Drug tables not found, initializing schema and seed data...");
            }

            ClassPathResource resource = new ClassPathResource("sql/med_purchase.sql");
            if (!resource.exists()) {
                log.warn("med_purchase.sql not found under classpath:/sql, skip init");
                return;
            }
            String sql;
            try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
                sql = br.lines().collect(Collectors.joining("\n"));
            }
            // 简单分割执行；注意忽略空行
            for (String stmt : sql.split(";\\s*\n")) {
                String s = stmt.trim();
                if (s.isEmpty()) continue;
                try {
                    jdbcTemplate.execute(s);
                } catch (Exception ex) {
                    log.warn("Execute init SQL failed: {} - {}", abbreviate(s, 80), ex.getMessage());
                }
            }
            log.info("Drug module schema initialized.");
        } catch (Exception e) {
            log.error("Init drug module failed", e);
        }
    }

    private static String abbreviate(String s, int max) {
        if (s == null) return null;
        if (s.length() <= max) return s;
        return s.substring(0, max) + "...";
    }
}

